import 'dart:convert';

import 'package:flutter/material.dart';
import '../../../../models/interface_info_model.dart';
import '../../../../services/jsonParserService.dart';
import '../../../../models/request_param.dart';
import '../../../../models/project_menu_model.dart';
import 'package:get/get.dart';
import '../../../../models/interface_model.dart';
import '../../../../models/field_info.dart';
import '../../../../services/httpsClient.dart';
import '../../../../services/messageUtil.dart';

class InterfaceController extends GetxController {
  //TODO: Implement InterfaceController

  bool isLoading = true; //请求防抖控制
  HttpsClient httpsClient = HttpsClient();
  TextEditingController searchController = TextEditingController();
  //左侧分组数据
  RxList<ProjectMenuItemModel?> leftProjectMenuList =
      <ProjectMenuItemModel?>[].obs;

  // 存储每个分组项的悬停状态
  var hoverStates = <int, bool>{}.obs;
  //右侧接口数据
  RxList<InterfaceItemModelData?> interfaceList =
      <InterfaceItemModelData?>[].obs;
  RxInt projectId = 0.obs; //当前项目id
  //当前选中的视图索引
  RxInt currentViewIndex = 0.obs;
  //新增项目分类信息
  RxString createProjectMenuName = ''.obs;
  //编辑项目分类信息
  RxString editProjectMenuName = ''.obs;

  //当前选中的分类id
  RxInt currentMenuId = 0.obs;
  //当前选中的接口id
  RxInt currentInterfaceId = 0.obs;
  //接口总数
  RxInt totalInterface = 0.obs;
  //当前页码
  RxInt currentPage = 1.obs;
  //总页数
  RxInt totalPages = 1.obs;
  //每页数量
  RxInt pageSize = 10.obs;
  //添加新接口时选中的分类
  var selectedValue = 0.obs;
  //添加新接口时接口名称
  RxString createInterfaceName = ''.obs;
  //添加新接口时接口地址
  RxString createInterfacePath = ''.obs;
  //编辑接口时接口名称
  RxString editInterfaceName = ''.obs;
  //编辑接口时接口地址
  RxString editInterfacePath = ''.obs;

  //添加新接口时选中的分类
  var selectedMethodValue = 1.obs;
  List methodList = [
    {"id": 1, "title": "GET"},
    {"id": 2, "title": "POST"},
    {"id": 3, "title": "PUT"},
    {"id": 4, "title": "DELETE"},
  ];
  //接口详情标签栏
  List interfaceInfoTabList = [
    {"id": 1, "title": "预览"},
    {"id": 2, "title": "编辑"},
  ];
  //接口详情标签栏当前选中索引
  RxInt currentInterfaceInfoTabIndex = 1.obs;
  //接口详情请求参数选项卡
  RxString selectedRequestParameTab = 'Body'.obs; // 当前选中的选项卡
  //接口详情请求参数body-form选项卡内容
  RxList<FormParam> formParams = <FormParam>[].obs;
  //接口详情请求参数query选项卡内容
  RxList<QueryParam> queryParams = <QueryParam>[].obs;
  //接口详情请求参数header选项卡内容
  RxList<HeaderParam> headerParams = <HeaderParam>[].obs;
  //接口详情返回数据选项卡
  var interfaceInfo = InterfaceInfoDataModel().obs;
  RxString selectedJsonTab = 'JSON'.obs; // 当前选中的选项卡
  // final RxString jsonInput = "".obs;
  // final RxList<FieldInfo> fields = <FieldInfo>[].obs;
  final RxList<FieldInfo> responseFields = <FieldInfo>[].obs;

  final RxString jsonInput = ''.obs;
  final RxString jsonOutput = ''.obs;
  final JsonParserService _parserService = JsonParserService();
  final List<FlatJsonItem> jsonList = <FlatJsonItem>[].obs;
  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  //设置当前项目id
  void setProjectId(int id) {
    projectId.value = id;
    getLeftProjectMenuData();
    getInterfaceListData();
    update();
  }

  //切换当前选中视图
  void changeCurrentViewIndex(int index, int menuId, int interfaceId) {
    currentViewIndex.value = index;
    currentMenuId.value = menuId;
    currentInterfaceId.value = interfaceId;
    if (interfaceId > 0) {
      getInterfaceInfoData(interfaceId);
    }
    selectedValue.value = menuId;

    currentPage.value = 1;
    getInterfaceListData();
    update();
  }

  // 切换页码
  void changePage(int page) {
    if (page >= 1 && page <= totalPages.value) {
      currentPage.value = page;
      getInterfaceListData();
      update();
    }
  }

  // 更新悬停状态
  void setHoverState(int id, bool isHovered) {
    hoverStates[id] = isHovered;
    update();
  }

  //改变接口详情顶部tab切换
  void changeInterfaceInfoTabsIndex(index) {
    currentInterfaceInfoTabIndex.value = index;
  }

  //改变接口详情请求参数选项卡
  void changeRequestParameTab(String tab) {
    selectedRequestParameTab.value = tab;
  }

  // 添加新字段
  void addInterfaceBodyFormParam() {
    formParams.add(FormParam());
    update();
  }

  //删除接口详情请求参数body-form选项卡内容
  void removeInterfaceBodyFormParam(int index) {
    formParams.removeAt(index);
    update();
  }

  // 添加新字段
  void addInterfaceQueryParam() {
    queryParams.add(QueryParam());
    update();
  }

  //删除接口详情请求参数query选项卡内容
  void removeInterfaceQueryParam(int index) {
    queryParams.removeAt(index);
    update();
  }

  // 添加新字段
  void addInterfaceHeaderParam() {
    headerParams.add(HeaderParam());
    update();
  }

  //删除接口详情请求参数header选项卡内容
  void removeInterfaceHeaderParam(int index) {
    headerParams.removeAt(index);
    update();
  }

  //获取项目分类信息
  getLeftProjectMenuData() async {
    var response = await httpsClient.get(
      "v1/project/menu_list",
      params: {'project_id': projectId.value, 'search': searchController.text},
    );
    if (response != null) {
      var group = ProjectMenuModel.fromJson(response.data);
      if (group.data != null && group.data!.isNotEmpty) {
        leftProjectMenuList.value = group.data!;
        // 初始化每个分组项的悬停状态为 false
        for (var item in leftProjectMenuList.value) {
          hoverStates[item?.id ?? 0] = false;
        }
      } else {
        leftProjectMenuList.value = [];
      }
      update();
    }
  }

  //获取接口列表
  getInterfaceListData() async {
    var response = await httpsClient.get(
      "v1/interface/list",
      params: {
        'project_id': projectId.value,
        'menu_id': currentMenuId.value,
        'page': currentPage.value,
        'page_size': pageSize.value,
      },
    );
    if (response != null) {
      var group = InterfaceModel.fromJson(response.data);
      if (group.data?.items != null && group.data!.items!.isNotEmpty) {
        interfaceList.value = group.data!.items ?? [];
      } else {
        interfaceList.value = [];
      }
      totalPages.value =
          ((group.data?.total ?? 0).toInt() /
                  (group.data?.limit ?? pageSize.value))
              .ceil();
      totalInterface.value = group.data?.total ?? 0;
      update();
    }
  }

  //删除项目分类
  deleteProjectMenu(int id) async {
    if (isLoading) {
      isLoading = false;

      var response = await httpsClient.post(
        "v1/project/del_menu",
        data: {'project_id': projectId.value, "menu_id": id},
      );

      if (response != null) {
        if (response.data['code'] == 0) {
          MessageUtil.showSuccess(
            message: "删除成功",
            config: MessageUtilConfig(
              duration: const Duration(seconds: 1),
              indicatorColor: Colors.green,
            ),
          );
          //重新请求左侧分类数据
          leftProjectMenuList.clear();
          getLeftProjectMenuData();
          //请刷新当前接口列表
          interfaceList.clear();
          currentPage.value = 1;
          getInterfaceListData();
        } else {
          MessageUtil.showError(message: response.data["message"]);
        }
      } else {
        MessageUtil.showError(message: "网络异常");
      }
      isLoading = true;
    }
  }

  //删除接口
  deleteInterface(int id) async {
    if (isLoading) {
      isLoading = false;

      var response = await httpsClient.post(
        "v1/interface/del",
        data: {'project_id': projectId.value, "interface_id": id},
      );

      if (response != null) {
        if (response.data['code'] == 0) {
          MessageUtil.showSuccess(
            message: "删除成功",
            config: MessageUtilConfig(
              duration: const Duration(seconds: 1),
              indicatorColor: Colors.green,
            ),
          );
          //重新请求左侧分类数据
          leftProjectMenuList.clear();
          getLeftProjectMenuData();
          //请刷新当前接口列表
          interfaceList.clear();
          currentPage.value = 1;
          getInterfaceListData();
        } else {
          MessageUtil.showError(message: response.data["message"]);
        }
      } else {
        MessageUtil.showError(message: "网络异常");
      }
      isLoading = true;
    }
  }

  // 提交新增项目分类表单
  void submitProjectMenuForm() async {
    if (isLoading) {
      isLoading = false;
      var response = await httpsClient.post(
        "v1/project/create_menu",
        data: {
          "name": createProjectMenuName.value,
          "project_id": projectId.value,
        },
      );

      if (response != null) {
        if (response.data['code'] == 0) {
          MessageUtil.showSuccess(
            message: "添加成功",
            config: MessageUtilConfig(
              duration: const Duration(seconds: 1),
              indicatorColor: Colors.green,
            ),
          );
          //重新请求左侧分类数据
          leftProjectMenuList.clear();
          getLeftProjectMenuData();
          // 关闭对话框
          Get.back();
        } else {
          MessageUtil.showError(message: response.data["message"]);
        }
      } else {
        MessageUtil.showError(message: "网络异常");
      }
      isLoading = true;
    }
  }

  // 提交编辑项目分类表单
  void submitEditProjectMenuForm(int menuId) async {
    if (isLoading) {
      isLoading = false;
      var response = await httpsClient.post(
        "v1/project/edit_menu",
        data: {"name": editProjectMenuName.value, "menu_id": menuId},
      );

      if (response != null) {
        if (response.data['code'] == 0) {
          MessageUtil.showSuccess(
            message: "添加成功",
            config: MessageUtilConfig(
              duration: const Duration(seconds: 1),
              indicatorColor: Colors.green,
            ),
          );
          //重新请求左侧分类数据
          leftProjectMenuList.clear();
          getLeftProjectMenuData();
          // 关闭对话框
          Get.back();
        } else {
          MessageUtil.showError(message: response.data["message"]);
        }
      } else {
        MessageUtil.showError(message: "网络异常");
      }
      isLoading = true;
    }
  }

  // 提交新增接口表单
  void submitInterfaceForm() async {
    if (isLoading) {
      isLoading = false;
      var response = await httpsClient.post(
        "v1/interface/create",
        data: {
          "name": createInterfaceName.value,
          "project_id": projectId.value,
          "menu_id": selectedValue.value,
          "path": createInterfacePath.value,
          "method": selectedMethodValue.value,
        },
      );

      if (response != null) {
        if (response.data['code'] == 0) {
          MessageUtil.showSuccess(
            message: "添加成功",
            config: MessageUtilConfig(
              duration: const Duration(seconds: 1),
              indicatorColor: Colors.green,
            ),
          );
          //重新请求左侧分类数据
          leftProjectMenuList.clear();
          getLeftProjectMenuData();
          //请刷新当前接口列表
          interfaceList.clear();
          currentPage.value = 1;
          getInterfaceListData();
          // 关闭对话框
          Get.back();
        } else {
          MessageUtil.showError(message: response.data["message"]);
        }
      } else {
        MessageUtil.showError(message: "网络异常");
      }
      isLoading = true;
    }
  }

  //获取接口详情
  void getInterfaceInfoData(int interfaceId) async {
    var response = await httpsClient.get(
      "v1/interface/info",
      params: {"interface_id": interfaceId, "project_id": projectId.value},
    );
    if (response != null) {
      if (response.data['code'] == 0) {
        var group = InterfaceInfoDataModel.fromJson(response.data["data"]);
        
        interfaceInfo.value = group;

        editInterfaceName.value = group.name ?? '';
        editInterfacePath.value = group.path ?? '';
        selectedValue.value = group.menuId!;
        selectedMethodValue.value = group.method!;
        formParams.clear();
        queryParams.clear();
        headerParams.clear();

        group.body?.forEach((element) {
          formParams.add(
            FormParam(
              fieldName: element?.fieldName ?? '',
              type: element?.type ?? 'text',
              exampleValue: element?.exampleValue ?? '',
              isRequired: element?.isRequired ?? '否',
              remark: element?.remark ?? '',
            ),
          );
        });
        group.query?.forEach((element) {
          queryParams.add(
            QueryParam(
              fieldName: element?.fieldName ?? '',
              isRequired: element?.isRequired ?? '否',
              exampleValue: element?.exampleValue ?? '',
              remark: element?.remark ?? '',
            ),
          );
        });
        group.header?.forEach((element) {
          headerParams.add(
            HeaderParam(
              fieldName: element?.fieldName ?? '',
              value: element?.value ?? '',
              remark: element?.remark ?? '',
            ),
          );
        });

        // 加载响应字段
        if (response.data["data"]["json"] != null) {
          final responseSchema = (response.data["data"]["json"] as List)
              .map((item) => FieldInfo.fromApiFormat(item))
              .toList();
          responseFields.assignAll(responseSchema);

          final jsonDataList = (response.data["data"]["json"] as List)
            .map((e) => InterfaceInfoDataJsonModel.fromJson(e))
            .toList();
            
          // 初始化扁平列表
          jsonList.assignAll(_flattenTree(jsonDataList));
        } else {
          responseFields.clear();
          jsonList.clear();
        }

        update();
      } else {
        MessageUtil.showError(message: response.data["message"]);
      }
    } else {
      MessageUtil.showError(message: "网络异常");
    }
  }
  
  List<FlatJsonItem> _flattenTree(List<InterfaceInfoDataJsonModel> tree, [int level = 0]) {
    List<FlatJsonItem> result = [];
    for (var node in tree) {
      result.add(FlatJsonItem(item: node, level: level));
      if (node.children != null && node.children!.isNotEmpty) {
        result.addAll(_flattenTree(node.children!, level + 1));
      }
    }
    return result;
  }

  void toggleExpand(int index) {
    final item = jsonList[index];
    if (item.item.children == null || item.item.children!.isEmpty) return;

    item.isExpanded = !item.isExpanded;
    if (item.isExpanded) {
      // 插入子节点
      final children = _flattenTree(item.item.children!, item.level + 1);
      jsonList.insertAll(index + 1, children);
    } else {
      // 移除所有子节点
      int removeCount = 0;
      for (int i = index + 1; i < jsonList.length; i++) {
        if (jsonList[i].level > item.level) {
          removeCount++;
        } else {
          break;
        }
      }
      jsonList.removeRange(index + 1, index + 1 + removeCount);
    }
    update();
  }

  // 提交编辑接口表单
  void submitEditInterfaceForm() async {
    if (isLoading) {
      isLoading = false;

      // 转换为服务器要求的格式
      final queryData = queryParams.map((field) => field.toMap()).toList();
      final headerData = headerParams.map((field) => field.toMap()).toList();
      final bodyData = formParams.map((field) => field.toMap()).toList();
      var response = await httpsClient.post(
        "v1/interface/edit",
        data: {
          "interface_id": currentInterfaceId.value,
          "name": editInterfaceName.value,
          "project_id": projectId.value,
          "menu_id": selectedValue.value,
          "path": editInterfacePath.value,
          "method": selectedMethodValue.value,
          "body": bodyData,
          "query": queryData,
          "header": headerData,
          'json': responseFields.map((field) => field.toApiFormat()).toList(),
        },
      );
      if (response != null) {
        if (response.data['code'] == 0) {
          MessageUtil.showSuccess(
            message: "编辑成功",
            config: MessageUtilConfig(
              duration: const Duration(seconds: 1),
              indicatorColor: Colors.green,
            ),
          );
          // 刷新接口
          getInterfaceInfoData(currentInterfaceId.value);
        } else {
          MessageUtil.showError(message: response.data["message"]);
        }
      } else {
        MessageUtil.showError(message: "网络异常");
      }
      isLoading = true;
      update();
    }
  }

  // 解析JSON数据
  void parseJsonData() {
    try {
      final parsedFields = _parserService.parseJsonString(jsonInput.value);
      responseFields.assignAll(parsedFields);
      // 关闭对话框
      Get.back();
    } catch (e) {
      print("JSON解析错误: $e");
    }
  }

  void updateFieldName(String fieldId, String newName) {
    final updatedFields = _updateFieldInList(responseFields, fieldId, (field) {
      return field.copyWith(name: newName);
    });

    if (updatedFields != null) {
      responseFields.assignAll(updatedFields);
    }
  }

  void updateFieldDescription(String fieldId, String newDescription) {
    final updatedFields = _updateFieldInList(responseFields, fieldId, (field) {
      return field.copyWith(description: newDescription);
    });

    if (updatedFields != null) {
      responseFields.assignAll(updatedFields);
    }
  }

  void updateFieldType(String fieldId, FieldType newType) {
    final updatedFields = _updateFieldInList(responseFields, fieldId, (field) {
      // 如果类型改为对象或数组，初始化空的children
      List<FieldInfo>? newChildren = field.children;
      if ((newType == FieldType.object || newType == FieldType.array) &&
          field.children == null) {
        newChildren = [];
      } else if (newType != FieldType.object && newType != FieldType.array) {
        newChildren = null;
      }

      return field.copyWith(type: newType, children: newChildren);
    });

    if (updatedFields != null) {
      responseFields.assignAll(updatedFields);
    }
  }

  // 添加字段
  void addField(String parentId, FieldInfo newField) {
    final updatedFields = _updateFieldInList(responseFields, parentId, (
      parentField,
    ) {
      if (parentField.type != FieldType.object &&
          parentField.type != FieldType.array) {
        Get.snackbar('错误', '只能向对象或数组添加字段');
        return parentField;
      }

      final newChildren = List<FieldInfo>.from(parentField.children ?? []);
      newChildren.add(newField);

      return parentField.copyWith(children: newChildren);
    });

    if (updatedFields != null) {
      responseFields.assignAll(updatedFields);
    }
  }

  //删除字段
  void removeField(String fieldId) {
    // 先找到要删除的字段的父字段
    final parentField = _parserService.findParentField(responseFields, fieldId);

    if (parentField != null && parentField.children != null) {
      final updatedFields = _updateFieldInList(responseFields, parentField.id, (
        field,
      ) {
        final newChildren = field.children!
            .where((child) => child.id != fieldId)
            .toList();
        return field.copyWith(children: newChildren);
      });

      if (updatedFields != null) {
        responseFields.assignAll(updatedFields);
      }
    } else {
      // 如果没有父字段，说明是顶级字段
      final newFields = responseFields
          .where((field) => field.id != fieldId)
          .toList();
      responseFields.assignAll(newFields);
    }
  }

  // 更新字段
  List<FieldInfo>? _updateFieldInList(
    List<FieldInfo> fields,
    String fieldId,
    FieldInfo Function(FieldInfo) updateFn,
  ) {
    for (int i = 0; i < fields.length; i++) {
      if (fields[i].id == fieldId) {
        final updatedField = updateFn(fields[i]);
        final newFields = List<FieldInfo>.from(fields);
        newFields[i] = updatedField;
        return newFields;
      }

      if (fields[i].children != null && fields[i].children!.isNotEmpty) {
        final updatedChildren = _updateFieldInList(
          fields[i].children!,
          fieldId,
          updateFn,
        );
        if (updatedChildren != null) {
          final updatedField = fields[i].copyWith(children: updatedChildren);
          final newFields = List<FieldInfo>.from(fields);
          newFields[i] = updatedField;
          return newFields;
        }
      }
    }
    return null;
  }
}
